//
//  CSGXHomeSalePreviewBalanceController.m
//  CarSalesMS_GCX
//
//  Created by Ssky on 2016/10/31.
//  Copyright © 2016年 Tony. All rights reserved.
//

#import "CSGXHomeSalePreviewBalanceController.h"
#import "CSBalanceCell.h"
#import "CSGXBaseTableView.h"
#import "CSTextField.h"
#import "CSEditView.h"

#import "TOrderInfoModel.h"

#import "TOrderInfoDAL.h"
#import "TSaleInfoDAL.h"
#import "TGatheringDayDAL.h"

NSString * const balanceCellId = @"balanceCellId";

@interface CSGXHomeSalePreviewBalanceController () <UITableViewDataSource, UITableViewDelegate>

@end

@interface CSGXHomeSalePreviewBalanceController ()

@property (nonatomic,weak) UIView * vHeader;
/// 客户剩余
@property (nonatomic,weak) UILabel * lblRemain;
/// 混合收款
@property (nonatomic,weak) UIButton * btnGather;
/// 结账打印
@property (nonatomic,weak) UILabel * lblPrint;
/// 发货金额
@property (nonatomic,weak) UILabel * lblSend;
/// tvContent
@property (nonatomic,weak) CSGXBaseTableView * tvContent;
/// 优惠栏
@property (nonatomic,weak) UIView * vPrivilege;


@property (nonatomic, strong) TOrderInfoModel *prevBalanceOrderModel;
@property (nonatomic, strong) NSArray<TSaleInfoModel *> * saleListBalance;

@end

@implementation CSGXHomeSalePreviewBalanceController

//- (void)viewDidLoad {
//    [super viewDidLoad];
//
//
//}


#pragma mark - actions
#pragma mark insert into DB
- (void)btnCommitAction:(UIBarButtonItem *)rightCommit {
    // 提交到数据库，提交完毕之后弹出提示，接着返回到 homeVc。
    
    /*
     - 生成订单号
     - 计算list中所有saleModel的 totalPrice 之和
     - 构造 orderModel
     - 将orderModel存入数据库
     - 将saleModelList存入数据库
     */
    
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"提交" message:@"确认提交吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addAction:[UIAlertAction actionWithTitle:@"提交" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [CSGXProgressTool showMsgWithStatus:@"正在提交..." delay:-1];
        
        // call back
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            //将订单数据和商品数据提交到数据库
            BOOL isInSucc = [self commitOrderAndSalesIntoDb];
            [NSThread sleepForTimeInterval:1];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!isInSucc) {
                    [CSGXProgressTool showErrorWithStatus:@"提交失败！" delay:0.8];
                    return;
                }
                
                [CSGXProgressTool showSuccessWithStatus:@"提交成功！" delay:0.5];
                [CSUserDefaultsTool setOrderNo:nil]; //提交数据库成功，将本次订单清空。
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            });
        });
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)btnPrevPrintAction:(UIBarButtonItem *)rightPrevPrint {
    
}


- (void)btnGatherClick:(UIButton *)sender {
    
}


#pragma mark - methods

- (BOOL)commitOrderAndSalesIntoDb {
    BOOL isInSucc = [TSaleInfoDAL insertIntoTSaleInfoWithArr:self.saleListBalance];
    if (!isInSucc) {
        return NO;
    }
    NSInteger lastOrderId = [TOrderInfoDAL insertIntoDbWithOrderModel:self.prevBalanceOrderModel];
    if (lastOrderId <= 0) {
        return NO;
    }
    //收银表
    TGatheringDayModel *gatheringModel = [TGatheringDayDAL getGatheringDayModelWithOrderModel:self.prevBalanceOrderModel];
    NSInteger lastGatheringId = [TGatheringDayDAL insertIntoDbWithGatheringModel:gatheringModel];
    if (lastGatheringId <= 0) {
        return NO;
    }
    
    return YES;
}

- (CGFloat)calculateTotalPriceAllWithSaleList:(NSArray<TSaleInfoModel *> *)saleListB {
    CGFloat tPriceF = 0;
    for (TSaleInfoModel *model in saleListB) {
        tPriceF += model.sTotalMoney;
    }
    return tPriceF;
}

- (void)distribute {
    self.lblSend.text = [NSString stringWithFormat:@"发货金额：%.2f", self.prevBalanceOrderModel.orTotalMoney];
}

#pragma mark - table view data source and delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.saleListBalance.count;
}

- (CSBalanceCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //
    CSBalanceCell * cell = [tableView dequeueReusableCellWithIdentifier:balanceCellId forIndexPath:indexPath];
    cell.saleModelBalance = self.saleListBalance[indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}


//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 100;
//}

#pragma markl - setupUI
- (void)setNavBar {
    UIBarButtonItem * rightCommit = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(btnCommitAction:)];
    UIBarButtonItem * rightPrevPrint = [[UIBarButtonItem alloc] initWithTitle:@"预览打印" style:UIBarButtonItemStylePlain target:self action:@selector(btnPrevPrintAction:)];
    
    self.navigationItem.rightBarButtonItems = @[rightCommit, rightPrevPrint];
}

-(void) setupUI {
    self.view.backgroundColor = kColorCategoryButtonGray;
    
    //
    [self setNavBar];
    
    // header
    UIView * vHeader = [[UIView alloc] init];
    [self.view addSubview:vHeader];
    vHeader.backgroundColor = kColorHeaderPrintVc;
    
    [vHeader mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.view);
        make.height.offset(30);
    }];
    
    // 客户剩余
    UILabel * lblRemain = [UILabel gx_labelWithText:@"客户剩余--" fontSize:15 color:kColorWhite];
    [vHeader addSubview:lblRemain];
    
    [lblRemain mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.equalTo(vHeader);
        
    }];
    // 混合收款
    UIButton * btnGather = [UIButton gx_textButton:@"混合收款" fontSize:15 normalColor:kColorWhite selectedColor:kColorWhite];
    [vHeader addSubview:btnGather];
    btnGather.layer.borderWidth = 2;
    btnGather.layer.borderColor = (__bridge CGColorRef _Nullable)([UIColor whiteColor]);
    
    [btnGather addTarget:self action:@selector(btnGatherClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [btnGather mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.trailing.equalTo(vHeader);
    }];
    
    // 发货金额
    UILabel * lblSend = [UILabel gx_labelWithText:@"发货金额：" fontSize:15 color:kColorWhite];
    [vHeader addSubview:lblSend];
    
    [lblSend mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(vHeader);
        make.trailing.mas_equalTo(btnGather.mas_leading).offset(-10);
    }];
    
#pragma mark tvContent
    // tvContent
    CSGXBaseTableView * tvContent = [[CSGXBaseTableView alloc] init];
    [self.view addSubview:tvContent];
    
    tvContent.dataSource = self;
    [tvContent registerClass:[CSBalanceCell class] forCellReuseIdentifier:balanceCellId];
    
    tvContent.estimatedRowHeight = 100;
    //    tvContent.rowHeight = 100;
    tvContent.rowHeight = UITableViewAutomaticDimension;
    
    
    [tvContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vHeader.mas_bottom).offset(2);
        make.leading.trailing.equalTo(self.view);
    }];
    
    
    // 优惠栏
    UIView * vPrivilege = [[UIView alloc] init];
    [self.view addSubview:vPrivilege];
    
    vPrivilege.backgroundColor = [UIColor orangeColor];
    
    [vPrivilege mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tvContent.mas_bottom).offset(2);
        make.bottom.equalTo(self.view);
        make.leading.trailing.equalTo(self.view);
        make.height.offset(20);
    }];
    
    //footer
    UIView *vFooter = [[UIView alloc] init];
    [self.view addSubview:vFooter];
    
    vFooter.backgroundColor = kColorBar;
    
    [vFooter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(self.view).mas_offset(0);
    }];
    
    //footerPayType
    UIView *vFooterPayType = [[UIView alloc] init];
    [self.view addSubview:vFooterPayType];
    
    vFooterPayType.backgroundColor = [UIColor whiteColor];
    
    [vFooterPayType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(vFooter).mas_offset(0);
        make.height.mas_offset(20);
    }];
    
    CGFloat margin = 10;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    //  @{@"title":title, @"edit":edit}
    CSEditView *vYouhui = [CSEditView editViewWithDict:@{@"title":@"优惠：", @"edit":@"", @"fontSize":@(12)}];
    [vFooterPayType addSubview:vYouhui];
    
    [vYouhui mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(vFooterPayType).mas_offset(0);
        make.leading.equalTo(vFooterPayType).mas_offset(5);
        make.width.mas_offset(@((screenWidth - 2*margin) / 3.0));
    }];
    
    CSEditView *vShuaka = [CSEditView editViewWithDict:@{@"title":@"刷卡：", @"edit":@"", @"fontSize":@(12)}];
    [vFooterPayType addSubview:vShuaka];
    
    [vShuaka mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(vFooterPayType).mas_offset(0);
        make.leading.equalTo(vYouhui.mas_trailing).mas_offset(margin);
        make.width.equalTo(vYouhui);
    }];
    
    CSEditView *vXianjin = [CSEditView editViewWithDict:@{@"title":@"现金：", @"edit":@"", @"fontSize":@(12)}];
    [vFooterPayType addSubview:vXianjin];
    
    [vXianjin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(vFooterPayType).mas_offset(0);
        make.trailing.equalTo(vFooterPayType).mas_offset(-5);
        make.width.equalTo(vYouhui);
    }];
    
    UIView *txtBgView = [[UIView alloc] init];
    [vFooter addSubview:txtBgView];
    
    txtBgView.backgroundColor = kColorWhite;
    
    [txtBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(vFooter).mas_offset(0);
        make.top.equalTo(vFooterPayType.mas_bottom).mas_offset(15);
        make.height.mas_offset(20);
    }];
    
    
    //txtRemark
    CSTextField *txtRemark = [CSTextField gx_textFieldWithLineColor:[UIColor gx_colorWithRed:200 green:200 blue:200] lineWidth:2];
    [vFooter addSubview:txtRemark];
    
    txtRemark.placeholder = @"添加备注";
    txtRemark.font = [UIFont systemFontOfSize:13];
    txtRemark.backgroundColor = [UIColor whiteColor];
    
    [txtRemark mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vFooterPayType.mas_bottom).mas_offset(15);
        make.leading.equalTo(vFooter).mas_offset(5);
        make.trailing.equalTo(vFooter).mas_offset(-5);
        make.height.mas_offset(20);
    }];
    
    //vFooterPrint
    UIView *vFooterPrint = [[UIView alloc] init];
    [self.view addSubview:vFooterPrint];
    //    vFooterPrint.backgroundColor = [UIColor orangeColor];
    
    [vFooterPrint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(txtRemark.mas_bottom).mas_offset(0);
        make.leading.trailing.equalTo(vFooter);
        make.height.mas_offset(30);
    }];
    
    UILabel *lblPrint = [UILabel gx_labelWithText:@"打印" fontSize:12 color:nil];
    [vFooterPrint addSubview:lblPrint];
    
    [lblPrint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.equalTo(vFooterPrint).mas_offset(0);
    }];
    
    UILabel *lblFen = [UILabel gx_labelWithText:@"0份" fontSize:13 color:nil];
    [vFooterPrint addSubview:lblFen];
    
    [lblFen mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(vFooterPrint).mas_offset(0);
        make.leading.equalTo(lblPrint.mas_trailing).mas_offset(20);
    }];


    
    //
    [vFooter mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(vFooterPrint).mas_offset(0);
    }];
    
    //
    self.vHeader = vHeader;
    self.lblRemain = lblRemain;
    self.btnGather = btnGather;
    self.lblSend = lblSend;
    self.tvContent = tvContent;
    self.vPrivilege = vPrivilege;
    
    [self distribute];
}




#pragma mark - setter & getter

- (void)setPrevBalanceDict:(NSDictionary *)prevBalanceDict {
    _prevBalanceDict = prevBalanceDict;
    
    self.prevBalanceOrderModel = prevBalanceDict[@"orderModel"];
    self.saleListBalance = prevBalanceDict[@"saleList"];
}

@end
